#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#define F_CPU 8000000UL				// I used 8 MHZ as my frequency



volatile int global_inter;			//Global Interrupt Value; pre-defined in Atmel

int main(void)
{
	//-------------------------------Interrupt Section--------------------------------------------------
	sei();						    //sei() enables the interrupt
	EIMSK |= (1<<INT0);			    //External interrupt 0 is enabled
	EICRA |= (1<<ISC01);			//The interrupt is requested at the falling edge, as where the instructions.
	
	//------------------------------Set variables and declare what Ports will be outputs----------------
	int COUNT=0;		            //PINB counter, initialzed at 0 to get first value
	int SECONDCOUNT = 0;			    //A second counter used for the ten pulses on the ninth LED bar bit
	DDRB = 0xFF;				    //PORTB is set as output
	PORTB = COUNT;			        //PORTB is set equal to count, which is initially zero.
	DDRC = 0x05;	                //PC0 and PC1 are set as outputs


	//---------------------------------While loop-----------------------------------------------------------
	while(1)
	{
		_delay_ms(250);			    //Rising edge of the clock cycle, with the delay function.
		
		//---------------------------------Output PORTB---------------------------------------------------------
		COUNT++;					//Increment the count, which also increments PORTB since PORTB= COUNT
		PORTB = COUNT;			    //Output PORTB with the current value of COUNT

		//---------------------------------Keep track of the 9th LED, as instructed-----------------------------
		
		SECONDCOUNT++;		        //Increment this to catch every tenth pulse
		if(SECONDCOUNT==10)		    //If the SECONDCOUNT = 10, it is time for the ninth LED to turn on.
		{
			PORTC |= (1 << PORTC0); //PC0 is turned on here, it is used as my feed to PD2 (INT0)
		}
		if(SECONDCOUNT == 20)	    //At this point, the LED should turn off, since it is the second tenth pulse
		{
			global_inter++;		    //Global Counter ++.
			PORTC &= ~(1 << PORTC0);//PC0 is turned off here.
			SECONDCOUNT = 0;		//Clear the Counter to 0 again, so we can keep track of the tenth pulse again
		}
		_delay_ms(250);			    //Falling edge of the clock cycle, with the delay function.
	}
}

//----------------------------------Interrupt Service Routine--------------------------------------------

ISR (INT0_vect)
{
	cli();					       //cli() is a pre-defined clear of the interrupt
	if(global_inter == 2)		   //Once the second falling edge occurs, we get it here.
	{
		PORTC |= (1 << PORTC1);	   //Turn on PC1, tenth LED on the BAR
	}
	if(global_inter == 4)		   //Once the fourth falling edge occurs, PC1 should be turned off
	{
		PORTC &= ~(1 << PORTC1);   //Turn off PC1
		global_inter = 0;		   //Counter Interrupt cleared to 0, to be able to catch the same cycles again.
	}
	sei();					       //sei() enables the interrupt
}

